package com.example.defaultshop;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BasketActivity extends Activity implements OnTaskCompleted {
	private ArrayList<Item> basket;

	private SwipeRefreshLayout swipe;
	private DrawerLayout layout;
	private ListView sidemenu, list;
	private Button order, back, home, settings;
	private TextView total;
	private Activity activity;

	private SharedPreferences preferences;
	private OnTaskCompleted callback;
	private ShopApplication app;
	private BasketTask task;
	
	private String[] items;
	
	private boolean copied;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_basket);
		
		activity = this;
		copied = getIntent().getBooleanExtra("copied", false);
		app = (ShopApplication) getApplicationContext();
		preferences = getSharedPreferences("DefaultShop", MODE_PRIVATE);
		
		items = new String[3 + app.getCards().size()];
		for (int i = 0; i < 3 + app.getCards().size(); i++) {
			switch (i) {
			case 0:
				items[i] = "Info";
				break;
			case 1:
				items[i] = "Indstillinger";
				break;
			case 2:
				items[i] = "Genbestil ordre";
				break;
			default:
				items[i] = app.getCards().get(i - 3).getName();
				break;
			}
		}

		callback = (OnTaskCompleted) this;
		
		layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        sidemenu = (ListView) findViewById(R.id.left_drawer);
        
        sidemenu.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, items));
        sidemenu.setOnItemClickListener(new DrawerItemClickListener());
		
        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
		swipe.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
        swipe.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				task = new BasketTask();
				task.execute();
			}
		});
		
		order = (Button) findViewById(R.id.btnOrder);
		order.setEnabled(false);
		order.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (app.getShop().getHours().equals("Lukket") || app.getShop().getOrders().equals("Lukket")) {
					Toast.makeText(v.getContext(), R.string.campaign_closed, Toast.LENGTH_LONG).show();
					Intent intent = new Intent(v.getContext(), CampaignActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					return;
				}
				try {
					String[] early = app.getShop().getOrders().split("-")[0].split(":");
					String[] late = app.getShop().getOrders().split("-")[1].split(":");
					int eh = Integer.parseInt(early[0]);
					int em = Integer.parseInt(early[1]);
					int lh = Integer.parseInt(late[0]);
					int lm = Integer.parseInt(late[1]);
					
					Calendar calendar = Calendar.getInstance();
					float now = calendar.getTimeInMillis();
					
					calendar.set(Calendar.HOUR_OF_DAY, eh);
					calendar.set(Calendar.MINUTE, em);
					if (calendar.getTimeInMillis() - now > 0) {
						dialog();
						return;
					}
					
					calendar.set(Calendar.HOUR_OF_DAY, lh);
					calendar.set(Calendar.MINUTE, lm);
					if (calendar.getTimeInMillis() - now <= 0) {
						dialog();
						return;
					}
				} catch (NumberFormatException e) { }
				
				if (basket.size() > 0) {
					Intent intent = new Intent(v.getContext(), CheckoutActivity.class);
					intent.putExtra("total", total());
					startActivity(intent);
				} else {
					Toast.makeText(v.getContext(), R.string.error_empty, Toast.LENGTH_LONG).show();
				}
			}
		});
		
		back = (Button) findViewById(R.id.btnBasketBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (copied) {
					finish();
				} else {
					Intent intent = new Intent(v.getContext(), CategoryActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				}
			}
		});
		
		home = (Button) findViewById(R.id.btnBasketHome);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), CampaignActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
		
		settings = (Button) findViewById(R.id.btnSettings);
		settings.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				layout.openDrawer(sidemenu);
			}
		});

		total = (TextView) findViewById(R.id.lblTotal);
		list = (ListView) findViewById(android.R.id.list);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				Item item = basket.get(position);
				if (item.getIdx() > 0) {
					RemoveDialog remove = new RemoveDialog(v.getContext(), app.getImage(item.getPicture()), item, position, app.getShop().getIdx(), app.getBasketId());
					remove.show();
				}
			}
		});

		swipe.setRefreshing(true);
		task = new BasketTask();
		task.execute();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);
		
		if (basket != null)
			basket.clear();
		
		app.stopTasks();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		Calendar date = Calendar.getInstance();
		Calendar deadline = app.getShop().getDeadline();
		if (date.get(Calendar.YEAR) != deadline.get(Calendar.YEAR) || date.get(Calendar.MONTH) != deadline.get(Calendar.MONTH) || date.get(Calendar.DAY_OF_MONTH) != deadline.get(Calendar.DAY_OF_MONTH)) {
			Intent intent = new Intent(this, CampaignActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}
	
	@Override
	public void onBackPressed() {
		if (copied) {
			finish();
		} else {
			Intent intent = new Intent(this, CategoryActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}

	@Override
	public void onTaskCompleted(boolean success) {
		if (success)
			list.invalidateViews();
	}
	
	public int total() {
		int price = 0;
		for (Item item : basket) {
			int temp = item.getPrice();
			price += temp * item.getAmount();
		}
		total.setText(" " + price + ",-");
		return price;
	}
	
	public void onItemRemoved(int index) {
		/*basket.remove(index);
		list.invalidateViews();
		total();*/

		swipe.setRefreshing(true);
		task = new BasketTask();
		task.execute();
	}
	
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
    	switch (position) {
		case 0:
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Server.INFO + app.getShop().getIdx()));
			startActivity(browserIntent);
			break;
		case 1:
			Intent customer = new Intent(this, CustomerActivity.class);
			startActivity(customer);
			break;
		case 2:
			Intent order = new Intent(this, OrderActivity.class);
			startActivity(order);
			break;
		default:
			Intent card = new Intent(this, CardActivity.class);
			card.putExtra("index", position - 3);
			startActivity(card);
			break;
		}
    	
        sidemenu.setItemChecked(position, false);
        layout.closeDrawer(sidemenu);
    }
	
	private void dialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		builder.setMessage(getResources().getString(R.string.campaign_open) + " " + app.getShop().getOrders())
				.setTitle(R.string.error_closed)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) { }
				});
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	private class BasketTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				String phone = preferences.getString("phone", "");
				InputStream in = Server.post(Server.BASKET, Server.getBasketXml(phone, app.getShop().getIdx(), app.getBasketId()));
				XmlPullParser parser = Server.toXmlParser(in);
				basket = XmlParser.getBasket(parser);
			} catch (IOException e) {
				Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (XmlPullParserException e) {
				Log.e("Shop", "XmlPullParserException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
			return true;
		}
		
		@Override
	    protected void onPostExecute(Boolean success) {
			swipe.setRefreshing(false);
			if (success) {
				order.setEnabled(true);
				for (int i = 0; i < basket.size(); i++)
	    			if (basket.get(i).isShowPicture())
	    				app.downloadImage(basket.get(i).getPicture(), callback, activity);
				
				total();
				BasketArrayAdapter adapter = new BasketArrayAdapter(activity, basket);
				list.setAdapter(adapter);
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(activity);
	    		builder.setMessage(R.string.error_basket)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								swipe.setRefreshing(true);
								task = new BasketTask();
								task.execute();
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
			}
		}
	}
}